最后一遍-L20-Valid Parentheses
Given a string s containing just the characters
'(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Constraints:
* 1 <= s.length <= 104
* s consists of parentheses only '()[]{}'.
NOTE:经典数据结构:Stack的问题
import java.util.Stack;
public class Solution {
public static void main(String[] args) {
System.out.println(isValid("()[]{}"));
System.out.println(isValid("[()]{}"));
System.out.println(isValid("[]{()}"));
System.out.println(isValid("[(){}]"));
System.out.println(isValid("[(){}"));
System.out.println(isValid("["));
}
/**
* s: 1 <= s.length <= 104
* consists of parentheses only '()[]{}'.
* ()[]{}
* */
public static boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
Character character = s.charAt(i);
if('('==character || '[' == character || '{' == character){
stack.push(character);
}else if(')' == character){
if(!stack.isEmpty() && stack.peek() == '('){
stack.pop();
}else{
return false;
}
}else if(']' == character){
if(!stack.isEmpty() && stack.peek() == '['){
stack.pop();
}else{
return false;
}
}else if('}' == character){
if(!stack.isEmpty() && stack.peek() == '{'){
stack.pop();
}else{
return false;
}
}
}
return stack.isEmpty();
}
}